<?php

namespace RMD\AccessBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;
use Doctrine\ORM\Tools\SchemaTool;

use RMD\AccessBundle\Entity\User;
use RMD\AccessBundle\Form\Type\UserType;

class SecurityController extends Controller
{
    public function loginAction(){
		if (!$this->getUser()) {
			$request = $this->getRequest();
			$session = $request->getSession();

			$error = '';
			if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
				$error = $request->attributes->has(SecurityContext::AUTHENTICATION_ERROR);
			} else {
				$error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
				$session->remove(SecurityContext::AUTHENTICATION_ERROR);

			}        
			return $this->render('RMDAccessBundle:Security:login.html.php',
					array('error' => $error, 'last_username' => $session->get(SecurityContext::LAST_USERNAME)));
		}
		return $this->redirect($this->generateUrl('_welcome'));
    }
    
    public function registerAction(Request $request){
		if (!$this->getUser()) {
			$user = new User();
			$form = $this->createForm(new UserType(), $user);
			//$logger = $this->get('logger');
			if ($request->isMethod('POST')) {

				$form->bind($request);
				if ($form->isValid()) {
					$factory = $this->get('security.encoder_factory');
					$encoder = $factory->getEncoder($user);
					$password = $encoder->encodePassword($form->get('password')->getData(), $user->getSalt());
					$user->setPassword($password);

					$em = $this->getDoctrine()->getEntityManager();
					//$tool = new SchemaTool($em);

					$em->persist($user);
					$em->flush();

					/*$metadata = $em->getClassMetadata('RMD\AccountBundle\Entity\Subscriber');
					$metadata->setTableName($user->getId() . '_' . $metadata->getTableName());
					$sql = $tool->getSchemaFromMetadata(array($metadata))->toSql($this->getDoctrine()->getConnection()->getDatabasePlatform());
					//var_dump($sql);
					$connection = $this->get('database_connection');
					$connection->query($sql[0]);*/

					return $this->redirect($this->generateUrl('acme_test_test2'));
				}
			}
			return $this->render('RMDAccessBundle:Security:register.html.php',
					array('form' => $form->createView()));
		}
		return $this->redirect($this->generateUrl('_welcome'));
    }
}
